package xyz.weizhi.rjwm.filter;
import com.alibaba.fastjson.JSON;
import com.sun.prism.impl.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.AntPathMatcher;
import xyz.weizhi.rjwm.common.baseContext;
import xyz.weizhi.rjwm.entity.vo.R;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author milian
 * @Date 2021/9/23 0023 10:28
 */
@WebFilter(filterName = "loginStateCheck",urlPatterns = "/*")
@Slf4j
public class LoginStateCheck implements Filter {
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //向下转型
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        //获取本次请求的url
        String  requestUrl = httpServletRequest.getRequestURI();
        //设置id
        baseContext.setThreadLocal((Long) httpServletRequest.getSession().getAttribute("employee"));
        log.info("拦截到请求：{}",requestUrl);
        //定义不需要处理的请求路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/login",
                "/user/sendSMS",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };
        //判断是否处理请求路径
        boolean result = check(requestUrl,urls);
        //不需要处理直接放行
        if (result){
            log.info("本次请求{}不需要处理",requestUrl);
            chain.doFilter(request, response);
            return;
        }
        //判断是否登录,如果登录直接放行
        if (httpServletRequest.getSession().getAttribute("employee")!=null){
            Long userId = (Long) httpServletRequest.getSession().getAttribute("employee");
            baseContext.setThreadLocal(userId);
            chain.doFilter(request, response);
            return;
        }
        if (StringUtils.isBlank(httpServletRequest.getHeader("Referer"))){
            if ( PATH_MATCHER.match("/backend/**",requestUrl)){
                httpServletResponse.sendRedirect("http://localhost:8080/backend/page/login/login.html");
            }else {
                httpServletResponse.sendRedirect("http://localhost:8080/front/page/login.html");
            }


            return;
        }
        if ( httpServletRequest.getSession().getAttribute("user")!=null) {
            Long userId = (Long) httpServletRequest.getSession().getAttribute("user");
            baseContext.setThreadLocal(userId);
            chain.doFilter(request,response);
            return;
        }
        //处理未登录逻辑
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }
    public boolean check(String requestUrl,String[] urls){
        for (String url : urls) {
            if ( PATH_MATCHER.match(url,requestUrl)) {
               return true;
            }
        }
        return false;
    }
}
